<template>
	<a-modal :visible="props.visible" width="90vw" centered destroyOnClose @ok="handleOk" @cancel="cancel" :maskClosable="false">
		<template #title>
			<span>编辑同住人</span>
			<a-button class="ml20" size="small" type="primary" @click="onClickToAddTogether">添加同住人</a-button>
		</template>
		<vxe-table ref="togetherTable" :data="tableData" v-bind="togetherTableOption">
			<vxe-column min-width="120px" align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					姓名
				</template>
				<template #default="{row, rowIndex}">
					<a-input v-model:value.trim="row.name" :bordered="false" placeholder="请输入姓名" />
				</template>
			</vxe-column>
			<vxe-column min-width="120px" align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					手机号
				</template>
				<template #default="{row, rowIndex}">
					<a-input v-model:value.trim="row.phone" :bordered="false" placeholder="请输入手机号" />
				</template>
			</vxe-column>
			<vxe-column width="140px" align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					性别
				</template>
				<template #default="{row, rowIndex}">
					<a-radio-group v-model:value="row.gender">
						<a-radio :value="1">男</a-radio>
						<a-radio :value="2">女</a-radio>
					</a-radio-group>
				</template>
			</vxe-column>
			<vxe-colgroup align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					证件信息
				</template>
				<vxe-column width="120px" align="center" header-class-name="display-none">
					<template #default="{row, rowIndex}">
						<a-select v-model:value="row.certificationType" :bordered="false" :options="options.certificateTypes" />
					</template>
				</vxe-column>
				<vxe-column min-width="180px" align="center" header-class-name="display-none">
					<template #default="{row, rowIndex}">
						<a-input v-model:value.trim="row.identityCard" :bordered="false" placeholder="请输入证件号" />
					</template>
				</vxe-column>
			</vxe-colgroup>
			<vxe-column width="120px" align="center">
				<template #header>
					<span v-color="{color: 'danger'}">*</span>
					关系
				</template>
				<template #default="{row, rowIndex}">
					<a-select v-model:value="row.renterRelation" :bordered="false" :options="renterRelationList" placeholder="请选择关系" />
				</template>
			</vxe-column>
			<vxe-column title="证件" width="60px" align="center">
				<template #default="{row, rowIndex}">
					<a @click=";(certificateConfig.visible = true), (certificateConfig.renter = row)">
						<template v-if="row.frontImgUrl || row.rearImgUrl">
							<check-outlined />
						</template>
						<plus-outlined v-else />
					</a>
				</template>
			</vxe-column>
			<vxe-column title="操作" width="60px" align="center">
				<template #default="{row, rowIndex}">
					<a v-color="{color: 'danger'}" @click="onClickToRemoveRow(rowIndex, togetherTable)">
						<svg-icon icon-class="trash" />
					</a>
				</template>
			</vxe-column>
		</vxe-table>
		<span v-show="validate" v-color="{color: 'danger'}">{{ validate }}</span>
		<!-- <a-input v-model:value="validate" status="error" disabled :bordered="false" /> -->
	</a-modal>
	<certificate-upload-dialog v-model:visible="certificateConfig.visible" :imgs="certificateConfig.renter" />
</template>
<script lang="ts" setup>
	import {VxeTableInstance, VxeTableProps} from 'vxe-table'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import {Empty, FormInstance, Modal, message} from 'ant-design-vue'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import {CheckOutlined, PlusCircleFilled, MinusOutlined, PlusOutlined, QuestionCircleOutlined} from '@ant-design/icons-vue'
	import {renterRelationList} from '@/utils'
	import {onMounted, reactive, ref, watch, createVNode} from 'vue'
	import {checkIdCard, checkPhone, chenkInteger} from '@/utils/check'
	import XEUtils from 'xe-utils'
	const emit = defineEmits(['update:visible', 'update:data', 'success'])
	const togetherTable = ref<VxeTableInstance>()
	const props = withDefaults(
		defineProps<{
			visible: boolean
			data?: any
		}>(),
		{
			visible: false,
			data: []
		}
	)
	const validate = ref('')
	const togetherTableOption = reactive<VxeTableProps>({
		size: 'mini',
		maxHeight: 200,
		border: true,
		cellStyle: {padding: 0},
		rowClassName: 'edit-table-row'
	})
	const tableData: any = ref([])
	const certificateConfig: any = ref({
		visible: false,
		renter: []
	})
	const options = reactive<any>({
		// 证件类型
		certificateTypes: Object.keys(CERTIFICATION_TYPE_MAP).map(key => ({
			label: CERTIFICATION_TYPE_MAP[key],
			value: Number(key)
		}))
	})
	watch(
		() => props.visible,
		val => {
			if (val) {
				console.log(XEUtils.clone(props.data, true))

				tableData.value = XEUtils.clone(props.data, true)
				togetherTable.value?.reloadData(tableData.value)
			}
		}
	)
	// 添加同住人
	const onClickToAddTogether = () => {
		tableData.value.push({
			gender: 1,
			certificationType: 1
		})

		togetherTable.value?.reloadData(tableData.value)
	}

	const cancel = () => {
		tableData.value = []
		togetherTable.value?.reloadData(tableData.value)
		emit('update:visible', false)
	}
	const validateFn = () => {
		const field = ['name', 'phone', 'gender', 'certificationType', 'identityCard', 'renterRelation']
		let validateRes = true
		let validateIdCard = true
		let validatePhone = true
		const res = tableData.value.every(e => {
			const valueList = Object.values(XEUtils.pick(e, field))
			console.log(valueList)
			if (validateRes) {
				validateRes = valueList.filter(e => e).length === valueList.length && field.length === valueList.length
			}
			if (e.phone && validatePhone) {
				e.phone && (validatePhone = checkPhone.test(e.phone))
			}
			if (e.identityCard && validateIdCard) {
				e.certificationType === 1 && e.identityCard && (validateIdCard = checkIdCard(e.identityCard))
			}
			return valueList.filter(e => e).length === valueList.length && field.length === valueList.length
		})
		console.log(res)

		if (!validateRes) {
			validate.value = '请完善同住人信息'
		} else if (!validatePhone) {
			validate.value = '电话号码有误，请核对'
		} else if (!validateIdCard) {
			validate.value = '证件号有误，请核对'
		} else {
			validate.value = ''
		}
		return validateRes && validatePhone && validateIdCard
	}
	const handleOk = () => {
		if (!validateFn()) {
			return
		}
		emit(
			'update:data',
			tableData.value.map(e => XEUtils.omit(e, ['_X_ROW_KEY']))
		)
		emit(
			'success',
			tableData.value.map(e => XEUtils.omit(e, ['_X_ROW_KEY']))
		)

		cancel()
	}
	const onClickToRemoveRow = (index: any, tableInstance: VxeTableInstance) => {
		Modal.confirm({
			title: '系统提示',
			content: '删除后无法恢复，确定删除？',
			centered: true,
			onOk() {
				tableInstance.data?.splice(index, 1)
				tableInstance.reloadData(tableInstance.data as [])
			}
		})
	}
</script>
<style lang="less" scoped>
	.ml20 {
		margin-left: 20px;
	}
</style>
